/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.scene.controller;

import com.alibaba.fastjson.JSONObject;
import com.koron.common.Excel;
import com.koron.common.StaffAttribute;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.permission.SPIAccountAnno;
import com.koron.common.web.Util;
import com.koron.hiddendanger.uitls.BusinessCode;
import com.koron.scene.domain.*;
import com.koron.scene.service.api.DangerousOperationService;
import com.koron.scene.utils.CryptoUtil;
import com.koron.scene.utils.ObjectUtil;
import com.koron.system.annotation.Log;
import com.koron.system.discrete.BusinessManipulation;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.ADOConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;
import org.swan.bean.MessageBean;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Api(tags = "dangerousOperation", description = "危险作业接口")
@RestController
@RequestMapping("/dangerousOperation")
@PropertySource({"classpath:deviceCheckFlow.properties"})
public class DangerousOperationController {
    private final static Logger logger= LoggerFactory.getLogger(DangerousOperationController.class);
    @Value("${secretKey}")
    private String secretKey;

    @Autowired
    private DangerousOperationService service;

    @Autowired
    private Util util;

    @ApiOperation("保存危险作业接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id，新增不传，修改传" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "projectId", value = "工程id" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "projectName", value = "工程名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "corpCode", value = "水司code", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "externalWork", value = "是否外部作业，0否，1是", required = true, dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "operationCategory", value = "作业分类(0_未使用模板（海宜公司），1_模板一，2_模板二)", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCategoryName", value = "作业分类名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketTypeName", value = "作业票类型名称", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCode", value = "作业编号" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationName", value = "作业名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "applicationUnit", value = "申请所在单位" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "applicationUnitName", value = "申请所在单位名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operatingUnit", value = "作业所在单位" , dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "operatingUnitName", value = "作业所在单位名称" , dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "constructionUnit", value = "施工作业单位" , dataType = "string", paramType = "query"),
            @ApiImplicitParam(name = "constructionUnitName", value = "施工作业单位名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationApplicant", value = "作业申请人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationApplicantName", value = "作业申请人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationExecutor", value = "作业执行人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationExecutorName", value = "作业执行人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "executorCertificateNo", value = "执行人特种作业证书" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hoistingCommander", value = "作业指挥人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hoistingCommanderName", value = "作业指挥人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "commanderCertificateNo", value = "指挥人特种作业证书" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationSupervisor", value = "作业监护人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationSupervisorName", value = "作业监护人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operatingLocation", value = "作业地点" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationDescription", value = "作业内容描述" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "originalMedium", value = "原有介质" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "powerAccessPoint", value = "电源接入点" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "liftingToolName", value = "吊装工具名" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "liftingWeight", value = "吊装重量" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "brokenCircuitReason", value = "断路原因" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "diagrammaticSketch", value = "断路地段示意图" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operatingVoltage", value = "工作电压" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "mainHazardFactors", value = "主要危害因素" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "samplingDetectionTime", value = "采样检测时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "samplingPoint", value = "采样点" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "analysisResults", value = "分析结果" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "analyst", value = "分析人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "analystName", value = "分析人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hotWorkMode", value = "动火方式，电焊，气焊，其他" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "breakGroundMode", value = "破土方式" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "hotWorkGrade", value = "动火等级，一级，二级，三级" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "workAtHeightGrade", value = "高空作业等级，1一级，2二级，3三级，4四级，0特殊" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "highAltitudeOperation", value = "高空作业高度" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationStartTime", value = "作业开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationEndTime", value = "作业结束时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "ratedLiftingCapacity", value = "额定起重量" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "actualLiftingWeight", value = "实际起重量" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationalEnvironment", value = "作业环境" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "metalStructureAndElectricalEquipment", value = "金属结构及电气设备" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "allParts", value = "全部零部件" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "safetyProtectionEquipment", value = "安全保护装置" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "supplementaryMeasures", value = "补充措施" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "educatedPerson", value = "受教育人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "educatedPersonName", value = "受教育人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "educatingPeople", value = "教育人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "educatingPeopleName", value = "教育人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "powerSupplyPerson", value = "送电人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "powerSupplyPersonName", value = "送电人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "powerSupplyTime", value = "送电时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "powerCutPerson", value = "停电人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "powerCutPersonName", value = "停电人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "powerCutTime", value = "停电时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "safetyMeasures", value = "主要安全措施json串" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTypes", value = "作业类型json串" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "personalProtectionAndEmergencys", value = "个人防护及应急措施json串" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "riskIdentificationAndMeasuress", value = "风险识别及防范措施json串" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "gasDetections", value = "气体检测json串" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "'状态,保存传0，提交传1", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "files", value = "上传的文件" , dataType = "file", paramType = "query"),
            @ApiImplicitParam(name = "keepFiles", value = "保留的文件地址" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delFiles", value = "删除的文件地址" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keepPreviewFiles", value = "保留的文件预览地址" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delPreviewFiles", value = "删除的文件预览地址" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "approver", value = "审批人userid json串,多个用逗号分隔" , paramType = "query", dataType = "String")
    }
    )
    @RequestMapping(value = "/save.htm", method = RequestMethod.POST)
    @Log(title = "保存危险作业接口", businessModule = "作业票", businessManipulation = BusinessManipulation.INSERT)
    public MessageBean<Integer> save(HttpServletRequest request, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore DangerousOperation bean,
                                     @ApiIgnore DangerousOperationFile fileBean, @ApiIgnore DangerousOperationApprover approverBean, @RequestParam(required = false) String safetyMeasures,
                                     @RequestParam(required = false) String hotWorks, @RequestParam(required = false) String blindPlates,
                                     @RequestParam(required = false) String operationTypes, @RequestParam(required = false) String personalProtectionAndEmergencys,
                                     @RequestParam(required = false) String riskIdentificationAndMeasuress, @RequestParam(required = false) String gasDetections,
                                     @RequestParam(required = false) final String usercode
    ) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        if (null == bean.getOperationCategory() || null == bean.getOperationTicketType()) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("作业分类和作业票类型不能为空");
            return msg;
        }
        if (StringUtils.isNotEmpty(operationTypes)) {
            List<OperationType> operationTypeList = JSONObject.parseArray(operationTypes, OperationType.class);
            bean.setOperationTypeList(operationTypeList);
        }
        if (StringUtils.isNotEmpty(personalProtectionAndEmergencys)) {
            List<PersonalProtectionAndEmergency> protectionAndEmergencyList = JSONObject.parseArray(personalProtectionAndEmergencys, PersonalProtectionAndEmergency.class);
            bean.setPersonalProtectionAndEmergencyList(protectionAndEmergencyList);
        }
        if (StringUtils.isNotEmpty(hotWorks)) {
            List<HotWork> hotWorkList = JSONObject.parseArray(hotWorks, HotWork.class);
            bean.setHotWorkList(hotWorkList);
        }
        if (StringUtils.isNotEmpty(blindPlates)) {
            List<BlindPlate> blindPlateList = JSONObject.parseArray(blindPlates, BlindPlate.class);
            bean.setBlindPlateList(blindPlateList);
        }
        if (StringUtils.isNotEmpty(safetyMeasures)) {
            List<SafetyMeasure> safetyMeasureList = JSONObject.parseArray(safetyMeasures, SafetyMeasure.class);
            // 获取安全措施现场照片
            if (safetyMeasureList != null && !safetyMeasureList.isEmpty()) {
                MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (SafetyMeasure safetyMeasure : safetyMeasureList) {
                            safetyMeasure.setFiles(standardMultipartHttpServletRequest.getFiles("files" + safetyMeasure.getSortNo()));
                        }
                    }
                }
            }
            bean.setSafetyMeasureList(safetyMeasureList);
        }
        if (StringUtils.isNotEmpty(riskIdentificationAndMeasuress)) {
            List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = JSONObject.parseArray(riskIdentificationAndMeasuress, RiskIdentificationAndMeasures.class);
            // 获取安全措施现场照片
            if (riskIdentificationAndMeasuresList != null && !riskIdentificationAndMeasuresList.isEmpty()) {
                MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (RiskIdentificationAndMeasures riskIdentificationAndMeasures : riskIdentificationAndMeasuresList) {
                            riskIdentificationAndMeasures.setFiles(standardMultipartHttpServletRequest.getFiles("files" + riskIdentificationAndMeasures.getSortNo()));
                        }
                    }
                }
            }
            bean.setRiskIdentificationAndMeasuresList(riskIdentificationAndMeasuresList);
        }
        if (StringUtils.isNotEmpty(gasDetections)) {
            List<GasDetection> gasDetectionList = JSONObject.parseArray(gasDetections, GasDetection.class);
            bean.setGasDetectionList(gasDetectionList);
        }
        if (bean.getOperationCategory() != 3) {
            if (bean.getExternalWork() == 0 && bean.getStatus() == 1 && ObjectUtil.checkObjAllFieldsIsNull(approverBean)) {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("审批人不能为空");
                return msg;
            }
        }
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        return service.save(bean, user, approverBean, fileBean);
    }

    @ApiOperation("获取secret密钥")
    @RequestMapping(value = "/getSecret", method = RequestMethod.GET)
    public MessageBean<String> getSecret() {
        MessageBean<String> msg = MessageBean.create(BusinessCode.SUCCESS.getCode(), "获取secret密钥，有效期5分钟", String.class);
        try {
            Map map = new HashMap();
            map.put("key", secretKey);
            map.put("time", System.currentTimeMillis());
            String encrypt = CryptoUtil.encrypt(map, "secret");
            if (StringUtils.isEmpty(encrypt)){
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription(BusinessCode.FAILURE.getDescription());
            }
            msg.setData(encrypt);
            return msg;
        } catch (Exception e) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription(BusinessCode.FAILURE.getDescription());
            return msg;
        }
    }


    @ApiOperation("二维码填报危险作业保存接口")
    @RequestMapping(value = "/saveByQrCode.htm", method = RequestMethod.POST)
    @Log(title = "二维码填报危险作业保存接口", businessModule = "作业票", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<Integer> saveByQrCode(HttpServletRequest request, @SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore DangerousOperation bean,
                                             @ApiIgnore DangerousOperationFile fileBean, @RequestParam(required = false) String safetyMeasures,
                                             @RequestParam(required = false) String hotWorks, @RequestParam(required = false) String blindPlates,
                                             @RequestParam(required = false) String operationTypes, @RequestParam(required = false) String personalProtectionAndEmergencys,
                                             @RequestParam(required = false) String riskIdentificationAndMeasuress, @RequestParam(required = false) String gasDetections,
                                             @RequestParam(required = false) final String userCode, @RequestParam(required = false) String approver

    ) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == bean.getOperationCategory() || null == bean.getOperationTicketType()) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("作业分类和作业票类型不能为空");
            return msg;
        }
        if (StringUtils.isNotEmpty(operationTypes)) {
            List<OperationType> operationTypeList = JSONObject.parseArray(operationTypes, OperationType.class);
            bean.setOperationTypeList(operationTypeList);
        }
        if (StringUtils.isNotEmpty(personalProtectionAndEmergencys)) {
            List<PersonalProtectionAndEmergency> protectionAndEmergencyList = JSONObject.parseArray(personalProtectionAndEmergencys, PersonalProtectionAndEmergency.class);
            bean.setPersonalProtectionAndEmergencyList(protectionAndEmergencyList);
        }
        if (StringUtils.isNotEmpty(hotWorks)) {
            List<HotWork> hotWorkList = JSONObject.parseArray(hotWorks, HotWork.class);
            bean.setHotWorkList(hotWorkList);
        }
        if (StringUtils.isNotEmpty(blindPlates)) {
            List<BlindPlate> blindPlateList = JSONObject.parseArray(blindPlates, BlindPlate.class);
            bean.setBlindPlateList(blindPlateList);
        }
        if (StringUtils.isNotEmpty(safetyMeasures)) {
            List<SafetyMeasure> safetyMeasureList = JSONObject.parseArray(safetyMeasures, SafetyMeasure.class);
            // 获取安全措施现场照片
            if (safetyMeasureList != null && !safetyMeasureList.isEmpty()) {
                MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (SafetyMeasure safetyMeasure : safetyMeasureList) {
                            safetyMeasure.setFiles(standardMultipartHttpServletRequest.getFiles("files" + safetyMeasure.getSortNo()));
                        }
                    }
                }
            }
            bean.setSafetyMeasureList(safetyMeasureList);
        }
        if (StringUtils.isNotEmpty(riskIdentificationAndMeasuress)) {
            List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = JSONObject.parseArray(riskIdentificationAndMeasuress, RiskIdentificationAndMeasures.class);
            // 获取安全措施现场照片
            if (riskIdentificationAndMeasuresList != null && !riskIdentificationAndMeasuresList.isEmpty()) {
                MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
                MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
                if (DefaultMultipartHttpServletRequest.class.isAssignableFrom(multipartRequest.getClass())) {
                    HttpServletRequest otherRequest = ((DefaultMultipartHttpServletRequest) multipartRequest).getRequest();
                    if (StandardMultipartHttpServletRequest.class.isAssignableFrom(otherRequest.getClass())) {
                        StandardMultipartHttpServletRequest standardMultipartHttpServletRequest = (StandardMultipartHttpServletRequest) otherRequest;
                        for (RiskIdentificationAndMeasures riskIdentificationAndMeasures : riskIdentificationAndMeasuresList) {
                            riskIdentificationAndMeasures.setFiles(standardMultipartHttpServletRequest.getFiles("files" + riskIdentificationAndMeasures.getSortNo()));
                        }
                    }
                }
            }
            bean.setRiskIdentificationAndMeasuresList(riskIdentificationAndMeasuresList);
        }
        if (StringUtils.isNotEmpty(gasDetections)) {
            List<GasDetection> gasDetectionList = JSONObject.parseArray(gasDetections, GasDetection.class);
            bean.setGasDetectionList(gasDetectionList);
        }
        if (StringUtils.isEmpty(approver)) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("二维码已失效");
            return msg;
        }
        // 将生成二维码的人作为当前用户
        String userid = JSONObject.parseArray(approver, String.class).stream().collect(Collectors.joining());
        List<StaffBean> staffBeanList = (List<StaffBean>) util.staff(userid, 2).getData();
        if (null != staffBeanList && staffBeanList.size() > 0) {
            user = staffBeanList.get(0);
        } else {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("二维码已失效");
            return msg;
        }
        bean.setUpdateTime(new Date());
        bean.setUpdateUser(user.getCode());
        bean.setUpdateUserName(user.getName());
        return service.saveByQrCode(bean, user, approver, fileBean);
    }

    @ApiOperation("流程中修改危险作业保存接口")
    @RequestMapping(value = "/flowSave.htm", method = RequestMethod.POST)
    @Log(title = "流程中修改危险作业保存接口", businessModule = "作业票", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<Integer> flowSave(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                         @ApiIgnore DangerousOperation bean, @ApiIgnore DangerousOperationFile fileBean,
                                         @RequestParam(required = false) String safetyMeasures,
                                         @RequestParam(required = false) String operationTypes,
                                         @RequestParam(required = false) String personalProtectionAndEmergencys,
                                         @RequestParam(required = false) String hotWorks,
                                         @RequestParam(required = false) String blindPlates,
                                         @RequestParam(required = false) String riskIdentificationAndMeasuress,
                                         @RequestParam(required = false) String gasDetections
    ) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        if (null == bean.getOperationCategory() || null == bean.getOperationTicketType()) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("作业票模板和作业票类型不能为空");
            return msg;
        }
        if (StringUtils.isNotEmpty(operationTypes)) {
            List<OperationType> operationTypeList = JSONObject.parseArray(operationTypes, OperationType.class);
            bean.setOperationTypeList(operationTypeList);
        }
        if (StringUtils.isNotEmpty(personalProtectionAndEmergencys)) {
            List<PersonalProtectionAndEmergency> protectionAndEmergencyList = JSONObject.parseArray(personalProtectionAndEmergencys, PersonalProtectionAndEmergency.class);
            bean.setPersonalProtectionAndEmergencyList(protectionAndEmergencyList);
        }
        if (StringUtils.isNotEmpty(hotWorks)) {
            List<HotWork> hotWorkList = JSONObject.parseArray(hotWorks, HotWork.class);
            bean.setHotWorkList(hotWorkList);
        }
        if (StringUtils.isNotEmpty(blindPlates)) {
            List<BlindPlate> blindPlateList = JSONObject.parseArray(blindPlates, BlindPlate.class);
            bean.setBlindPlateList(blindPlateList);
        }
        if (StringUtils.isNotEmpty(safetyMeasures)) {
            List<SafetyMeasure> safetyMeasureList = JSONObject.parseArray(safetyMeasures, SafetyMeasure.class);
            bean.setSafetyMeasureList(safetyMeasureList);
        }
        if (StringUtils.isNotEmpty(riskIdentificationAndMeasuress)) {
            List<RiskIdentificationAndMeasures> riskIdentificationAndMeasuresList = JSONObject.parseArray(riskIdentificationAndMeasuress, RiskIdentificationAndMeasures.class);
            bean.setRiskIdentificationAndMeasuresList(riskIdentificationAndMeasuresList);
        }
        if (StringUtils.isNotEmpty(gasDetections)) {
            List<GasDetection> gasDetectionList = JSONObject.parseArray(gasDetections, GasDetection.class);
            bean.setGasDetectionList(gasDetectionList);
        }
        return service.flowSave(bean, fileBean, user);
    }

    @ApiOperation("流程中危险作业签名保存接口")
    @RequestMapping(value = "/flowSignSave.htm", method = RequestMethod.POST)
    @Log(title = "流程中危险作业签名保存接口", businessModule = "作业票", businessManipulation = BusinessManipulation.UPDATE)
    public MessageBean<Integer> flowSignSave(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                             @RequestParam(required = true) String id, MultipartFile[] files
    ) {
        MessageBean<Integer> msg = new MessageBean<>();
        if (null == user) {
            msg.setCode(BusinessCode.NOT_LONGIN.getCode());
            msg.setDescription(BusinessCode.NOT_LONGIN.getDescription());
            return msg;
        }
        return ADOConnection.runTask(factory -> service.flowSignSave(factory, user, id, files), MessageBean.class);
    }


    @ApiOperation("删除危险作业接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "危险作业id", required = true, dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/delete.htm", method = RequestMethod.POST)
    @Log(title = "删除危险作业", businessModule = "作业票", businessManipulation = BusinessManipulation.DELETE)
    public MessageBean<Integer> deleteContingencyPlan(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                      @RequestParam(required = false) String usercode,
                                                      @RequestParam final String id) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        }
        return service.delete(id, user);
    }

    @ApiOperation("编码生成测试接口")
    @RequestMapping(value = "/testGetCode.htm", method = RequestMethod.POST)
    @Log(title = "编码生成测试", businessModule = "作业票", businessManipulation = BusinessManipulation.DELETE)
    public String testGetCode() {
        return ADOConnection.runTask(factory -> service.getCode(factory), String.class);
    }

    @ApiOperation("查询危险作业详情接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "危险作业id", required = true, dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/details.htm", method = RequestMethod.GET)
    public MessageBean<DangerousOperationBean> details(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), DangerousOperationBean.class);
        }
        return service.queryOne(id);
    }


    @ApiOperation("危险作业延期接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "危险作业id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "delayDate", value = "延期至（日期）,格式yyyy-MM-dd HH:mm:ss" , dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "delayDescription", value = "延期说明" , dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "approver", value = "审批人userid json串,多个用逗号分隔" , paramType = "query", dataType = "String")
    })
    @RequestMapping(value = "/delay.htm", method = RequestMethod.POST)
    public MessageBean<Integer> delay(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @ApiIgnore DangerousOperationApprover approver, @RequestParam final String id,
                                      @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date delayDate,
                                      @RequestParam(required = false) String delayDescription) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        }
        MessageBean<Integer> msg = new MessageBean<>();
        if (ObjectUtil.checkObjAllFieldsIsNull(approver)) {
            msg.setCode(BusinessCode.FAILURE.getCode());
            msg.setDescription("审批人不能为空");
            return msg;
        }
        return service.delay(user, id, delayDate, delayDescription, approver);
    }


    @ApiOperation("危险作业交底接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "危险作业id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "disclosureFiles", value = "交底上传的文件" , dataType = "file", paramType = "query"),
    })
    @RequestMapping(value = "/disclosure.htm", method = RequestMethod.POST)
    public MessageBean<Integer> disclosure(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id,
                                           @RequestParam(required = false) final MultipartFile[] disclosureFiles) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        }
        return ADOConnection.runTask(factory -> service.disclosure(factory, user, id, disclosureFiles), MessageBean.class);
    }

    @ApiOperation("确认危险作业完工接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "危险作业id", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "completionDescription", value = "完工说明" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "completionTime", value = "完工时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "personInCharge", value = "作业负责人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "personInChargeName", value = "作业负责人名称" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "completionConfirmer", value = "完工确认人" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "completionConfirmerName", value = "完工确认人名" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/confirm.htm", method = RequestMethod.POST)
    public MessageBean<Integer> confirm(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, @RequestParam final String id, @RequestParam(required = false) String completionDescription,
                                        @RequestParam(required = false) String completionTime, @RequestParam(required = false) String personInCharge,
                                        @RequestParam(required = false) String personInChargeName, @RequestParam(required = false) String completionConfirmer,
                                        @RequestParam(required = false) String completionConfirmerName) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        }
        return service.confirm(user, id, completionDescription, completionTime, personInCharge, personInChargeName, completionConfirmer, completionConfirmerName);
    }


    @ApiOperation("危险作业列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCategory", value = "作业分类(0_未使用模板，1_模板一，2_模板二)" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCategoryName", value = "作业分类(0_未使用模板，1_模板一，2_模板二)" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketTypeName", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCode", value = "作业票编号" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "作业票状态" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "keyword", value = "关键词" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/list.htm", method = RequestMethod.GET)
    public MessageBean<DataBean<DangerousOperation>> list(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                          @RequestParam(required = false) final String corpCode,
                                                          @RequestParam(required = false) final String operationCategory,
                                                          @RequestParam(required = false) final String operationTicketType,
                                                          @RequestParam(required = false) final String operationCategoryName,
                                                          @RequestParam(required = false) final String operationTicketTypeName,
                                                          @RequestParam(required = false) final String operationCode,
                                                          @RequestParam(required = false) final Integer status,
                                                          @RequestParam(required = false) final String startTime,
                                                          @RequestParam(required = false) final String endTime,
                                                          @RequestParam(required = false) String keyword,
                                                          @RequestParam Integer page,
                                                          @RequestParam Integer pageSize) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<DangerousOperation>> msg = service.list(corpCode, operationCategory, operationTicketType, operationCategoryName, operationTicketTypeName, operationCode, status, startTime, endTime, start, pageSize, keyword);
        if (null != msg.getData()) {
            msg.getData().setPageNo(page);
        }
        return msg;
    }

    @ApiOperation("根据危险作业分类和作业票类型查询安全防范措施接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "operationCategory", value = "作业分类(0_海宜，1_模板1，2_模板2)" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/getAllSafetyMeasure.htm", method = RequestMethod.GET)
    public MessageBean<List<SafetyMeasure>> getAllSafetyMeasure(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                                @RequestParam(required = false) final Integer operationCategory,
                                                                @RequestParam(required = false) final Integer operationTicketType) {
//        if (null == user) {
//            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
//        }
        return service.getAllSafetyMeasure(operationCategory, operationTicketType);
    }

    @ApiOperation("获取当前登录人所属公司，以及使用作业票分类")
    @RequestMapping(value = "/getUserCorpAndOperationCategory.htm", method = RequestMethod.GET)
    public MessageBean<Map> getUserCorpAndOperationCategory(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return service.getUserCorpAndOperationCategory(user);
    }

    @ApiOperation("根据危险作业分类和作业票类型查询作业类型接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "operationCategory", value = "作业分类(0_海宜，1_模板1，2_模板2)" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/getAllOperationType.htm", method = RequestMethod.GET)
    public MessageBean<List<OperationType>> getAllOperationType(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                                @RequestParam(required = false) final Integer operationCategory,
                                                                @RequestParam(required = false) final Integer operationTicketType) {
//        if (null == user) {
//            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
//        }
        return service.getAllOperationType(operationCategory, operationTicketType);
    }

    @ApiOperation("根据危险作业分类和作业票类型查询个人防护及应急措施接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "operationCategory", value = "作业分类(0_海宜，1_模板1，2_模板2)" , dataType = "int", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "int", paramType = "query")
    })
    @RequestMapping(value = "/getAllProtectionAndEmergency.htm", method = RequestMethod.GET)
    public MessageBean<List<PersonalProtectionAndEmergency>> getAllProtectionAndEmergency(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                                                          @RequestParam(required = false) final Integer operationCategory,
                                                                                          @RequestParam(required = false) final Integer operationTicketType) {
//        if (null == user) {
//            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
//        }
        return service.getAllProtectionAndEmergency(operationCategory, operationTicketType);
    }

    @ApiOperation("根据危险作业分类和作业票类型查询风险隐患和防范措施接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "operationCategory", value = "作业分类(0_海宜，1_模板1，2_模板2)" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "String", paramType = "query")
    })
    @RequestMapping(value = "/getAllRiskIdentificationAndMeasures.htm", method = RequestMethod.GET)
    public MessageBean<List<RiskIdentificationAndMeasures>> getAllRiskIdentificationAndMeasures(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                                                                @RequestParam(required = false) final Integer operationCategory,
                                                                                                @RequestParam(required = false) final Integer operationTicketType) {
//        if (null == user) {
//            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
//        }
        return service.getAllRiskIdentificationAndMeasures(operationCategory, operationTicketType);
    }

    @ApiOperation("流程中的业务数据")
    @ApiImplicitParam(name = "ids", value = "流程关联的业务ids", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/getProcessData.htm", method = {RequestMethod.GET})
    public MessageBean<?> getProcessData(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String ids) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), Integer.class);
        }
        return service.getProcessData(ids);
    }

    @ApiOperation("危险作业导出")
    @ApiImplicitParam(name = "id", value = "危险作业id", required = true, paramType = "query", dataType = "String")
    @RequestMapping(value = "/exports.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exports(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user, String id) {
        if (null == user) {
            return null;
        }
        MessageBean<DangerousOperationVo> msg = service.getDangerousOperation(id);
        if (null == msg.getData()) {
            return null;
        }
        DangerousOperationVo operation = msg.getData();
        Map<String, Object> map = new HashMap<>();
        map.put("data", operation);
        // TODO 根据不同的作业分类，作业票类型，选用不同的导出模板和btl脚本，共26种
        // 根据作业分类和作业票类型查找对应的模板
        Integer checkResult = service.check(operation.getOperationCategory(), operation.getOperationTicketType());
        StringBuilder pathStr = new StringBuilder();
        StringBuilder templateStr = new StringBuilder();
        String path = pathStr.append("static/excel/dangerousOperation").append(checkResult).append(".xlsx").toString();
        String template = templateStr.append("dangerousOperation").append(checkResult).append(".btl").toString();
        File targetFile = new File(path);
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream(path);
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile(operation.getOperationTicketTypeName(), targetFile, template, map);
    }

    @ApiOperation("危险作业列表导出")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketTypeName", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/exportList.htm", method = {RequestMethod.GET})
    public HttpEntity<?> exportList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                    @RequestParam(required = false) final String corpCode,
                                    @RequestParam(required = false) final String operationTicketType,
                                    @RequestParam(required = false) final String operationCode,
                                    @RequestParam(required = false) final Integer status,
                                    @RequestParam(required = false) final String startTime,
                                    @RequestParam(required = false) final String endTime
    ) {
        if (null == user) {
            return null;
        }
        List<DangerousOperationVo> list = service.exportList(corpCode, operationTicketType, operationCode, status, startTime, endTime);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        File targetFile = new File("static/excel/dangerousOperationList.xlsx");
        try {
            InputStream in = getClass().getClassLoader().getResourceAsStream("static/excel/dangerousOperationList.xlsx");
            FileUtils.copyInputStreamToFile(in, targetFile);
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
        }
        return Excel.createFile("作业票列表", targetFile, "dangerousOperationList.btl", map);
    }

    @ApiOperation("查询持有相关证照的人员")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "certificateTypeName", value = "证照类型名称" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/getStaffByCertificate.htm", method = RequestMethod.GET)
    public MessageBean<List<StaffBean>> getStaffByCertificate(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                              @RequestParam(required = false) final String corpCode,
                                                              @RequestParam(required = false) final String certificateTypeName) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        MessageBean<List<StaffBean>> msg = ADOConnection.runTask(factory -> service.getStaffByCertificate(factory, corpCode, certificateTypeName), MessageBean.class);
        return msg;
    }

    @ApiOperation("危险作业统计接口,根据公司，危险作业状态，时间段进行统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "统计开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "统计截止时间" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/analysis.htm", method = RequestMethod.GET)
    public MessageBean<List<DangerousOperationAnalysisBean>> dangerousOperationAnalysis(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                                                        @RequestParam(required = false) final String code,
                                                                                        @RequestParam(required = false) Integer status,
                                                                                        @RequestParam(required = false) String startTime,
                                                                                        @RequestParam(required = false) String endTime) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        if (null != status && status != 1 && status != 2 && status != 3) {
            return MessageBean.create(BusinessCode.FAILURE.getCode(), "状态参数不合法", null);
        }
        MessageBean<List<DangerousOperationAnalysisBean>> msg = service.dangerousOperationAnalysis(code, status, startTime, endTime);
        return msg;
    }

    @ApiOperation("危险作业统计接口,根据公司，时间段进行统计")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "统计开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "统计截止时间" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/dangerousOperationAnalysis.htm", method = RequestMethod.GET)
    public MessageBean<List<DangerousOperationAnalysis>> analysis(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                                  @RequestParam(required = false) final String code,
                                                                  @RequestParam(required = false) String startTime,
                                                                  @RequestParam(required = false) String endTime) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        return service.analysis(code, startTime, endTime);
    }


    @ApiOperation("首页工作台危险作业列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "corpCode", value = "水司code" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCategory", value = "作业分类(0_未使用模板，1_模板一，2_模板二)" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCategoryName", value = "作业分类(0_未使用模板，1_模板一，2_模板二)" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketType", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationTicketTypeName", value = "作业票类型（1临时用电作业，2有限空间作业，3起重吊装作业，4动火作业，5破土作业，6高空作业，7抽堵盲板作业，8设备检修作业，9断路安全作业）" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "operationCode", value = "作业票编号" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "status", value = "作业票状态" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "page", value = "当前页" , dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数" , dataType = "String", paramType = "query"),
    })
    @RequestMapping(value = "/homePageOperationList.htm", method = RequestMethod.POST)
    public MessageBean<DataBean<DangerousOperation>> homePageOperationList(@SPIAccountAnno @StaffAttribute("_user") @ApiIgnore StaffBean user,
                                                                           @RequestParam(required = false) final String corpCode,
                                                                           @RequestParam(required = false) final String operationCategory,
                                                                           @RequestParam(required = false) final String operationTicketType,
                                                                           @RequestParam(required = false) final String operationCategoryName,
                                                                           @RequestParam(required = false) final String operationTicketTypeName,
                                                                           @RequestParam(required = false) final String operationCode,
                                                                           @RequestParam(required = false) final Integer status,
                                                                           @RequestParam(required = false) final String startTime,
                                                                           @RequestParam(required = false) final String endTime,
                                                                           @RequestParam Integer page,
                                                                           @RequestParam Integer pageSize) {
        if (null == user) {
            return MessageBean.create(BusinessCode.NOT_LONGIN.getCode(), BusinessCode.NOT_LONGIN.getDescription(), null);
        }
        Integer start = null;
        if (page == null || page <= 0) {
            page = 1;
            if (pageSize == null || pageSize <= 0) {
                pageSize = 10;
            }
        }
        start = (page <= 1) ? 0 : (page - 1) * pageSize;
        MessageBean<DataBean<DangerousOperation>> msg = service.homePageOperationList(corpCode, operationCategory, operationTicketType, operationCategoryName, operationTicketTypeName, operationCode, status, startTime, endTime, start, pageSize);
        if (null != msg.getData()) {
            msg.getData().setPageNo(page);
        }
        return msg;
    }
}
